﻿using System;
using UnityEditor;
using UnityEngine;

namespace Miao.Editor
{
    public class SplitLine//在编辑器中绘制一条可拖动的分割线
    {
        public event Action OnDrag = delegate { };

        public float minX { get; set; }
        public float maxX { get; set; } = float.MaxValue;
        public float currentX { get; private set; }
        public float LineWidth { get; set; } = 2;

        public Color LineColor { get; set; } = Color.black;

        private bool Dragging;

        public SplitLine(float defaultX)
        {
            currentX = defaultX;
        }

        public void Draw()
        {
            Rect drawRect = new Rect(currentX, 0, LineWidth, 1080);
            EditorGUI.DrawRect(drawRect, LineColor);
            Event currentEvent = Event.current;
            Vector2 mousePosition = currentEvent.mousePosition;
            EditorGUIUtility.AddCursorRect(drawRect, MouseCursor.SplitResizeLeftRight);
            bool containsMouse = drawRect.Contains(mousePosition);
            switch (currentEvent.type)
            {
                case EventType.MouseDown: if (containsMouse) Dragging = true; return;
                case EventType.MouseUp: Dragging = false; return;
                case EventType.MouseDrag:
                    if (!Dragging) return;
                    currentX += currentEvent.delta.x;
                    currentX = Mathf.Clamp(currentX, minX, maxX);
                    OnDrag();
                    return;
            }
        }
    }
}
